package com.mlk.stock.service.impl;


import com.mlk.constant.EngConstant;
import com.mlk.core.component.page.Page;
import com.mlk.core.component.page.Pager;
import com.mlk.core.exception.GlobalException;
import com.mlk.core.util.ServerResponse;
import com.mlk.stock.mapper.EngStockDetailMapper;
import com.mlk.stock.po.EngStockDetail;
import com.mlk.stock.service.StockService;
import com.mlk.stock.vo.EngStockDetailVO;
import com.mlk.waste.mapper.EngWasteTypeTreeMapper;
import com.mlk.waste.po.EngWasteTypeTree;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

@Service
public class StockServiceImpl implements StockService {

    @Resource
    private EngStockDetailMapper engStockDetailMapper;

    @Resource
    private EngWasteTypeTreeMapper engWasteTypeTreeMapper;

    /**
     * 盘点操作
     * @param typeId
     * @param num
     * @return
     */
    @Override
    @Transactional
    public ServerResponse stockCal(Integer typeId, BigDecimal num) {


        BigDecimal oldNum = this.engWasteTypeTreeMapper.selectById(typeId).getStock();
        // 直接将库存的值修改为当前值
        int count = this.engWasteTypeTreeMapper.updateById(EngWasteTypeTree.builder().id(typeId).stock(num).build());

        if(count == 0){
            throw new GlobalException("盘点失败");
        }

        // 增加一个详情信息
        EngStockDetail detail = new EngStockDetail();
        detail.setCreateTime(new Date());
        detail.setTypeId(typeId);
        detail.setNum(num.subtract(oldNum));
        detail.setType(EngConstant.STOCK_OPS_TYPE.CAL_TYPE);
        count = this.engStockDetailMapper.insert(detail);
        if(count == 0){
            throw new GlobalException("盘点失败");
        }
        return ServerResponse.ok("盘点成功");
    }

    /**
     * 库存明细列表
     * @param detail
     * @return
     */
    @Override
    @Page
    public Pager detailPageList(EngStockDetailVO detail) {
        return Pager.adapt(this.engStockDetailMapper.selectForPage(detail));
    }
}
